/*
 * memory.c
 *
 *  Created on: Mar 4, 2012
 */

#include <stdlib.h>

#include "memory.h"

/*
 *	getLocation(int the_location)
 *		get lock
 *		store value into var
 *		release lock
 *		return var
 */
int getLocation_function(memory * mem_ptr, int the_location){

	if(the_location < mem_ptr->size){
		return mem_ptr->shared_memory[the_location];
	}
	else {
		return -1;
	}
}
/*
 *	setLocation(int, int)
 *		get lock
 *		modify data
 *		release lock
 *		return
 */
int setLocation_function(memory * mem_ptr, int the_location, int the_value){

	if(the_location < mem_ptr->size){
		mem_ptr->shared_memory[the_location] = the_value;
	}
	else {
		return -1;
	}

	return 0;
}

int up_function(memory * mem_ptr, int the_location){
	return mem_ptr->shared_memory[the_location]++;
}

int down_function(memory * mem_ptr, int the_location){
	if(mem_ptr->shared_memory[the_location] >= 1){
		mem_ptr->shared_memory[the_location]--;
		return 0;
	}
	else{
		//DANGER: location already allocated!
		return -1;
	}
}

 int check_location_function(memory * mem_ptr, int the_location){
	return mem_ptr->shared_memory[the_location];
}

memory * memory_init(int size){
	// 1 is subtracted to offset constant array declaration in struct to avoid C99 Flexible array member,
	// more details here: http://stackoverflow.com/questions/246977/flexible-array-members-in-c-bad/247040#247040
	memory *x = malloc(sizeof(memory));
	x->size = size;
	x->shared_memory = malloc(sizeof(int) * size);

	//x->shared_memory[20] = 9001;
	//printf("shared memory[20] is %d \n", x->shared_memory[20]);

	//x->getLocation = &getLocation_function;
	//x->setLocation = &setLocation_function;
	x->up = &up_function;
	x->down = &down_function;
	x->check_location = &check_location_function;

	//setup shared memory:
	int index = 0;
	while(index < size){
		x->shared_memory[index] = 1;
		index++;
	}


	//x->shared_memory;
	return x;
}


